
import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Input,
  message
} from 'antd';
import {
  SearchOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import axios from 'axios';


// API基础URL
const API_BASE_URL = "http://localhost:3000";

// 定义库存数据类型（匹配后端API）
interface InventoryItem {
  key: string;
  id: number;
  sort: string;
  code: number;
  name: string;
  cate: string;
  warning: number;
  fieldName: string;
  warehouse: string;
  reservoir: string;
  location: string;
  add: string;
  addtime: string;
}

const Query: React.FC = () => {
  const [inventoryItems, setInventoryItems] = useState<InventoryItem[]>([]);
  const [loading, setLoading] = useState(false);

  const [customerName, setCustomerName] = useState('');
  const [itemName, setItemName] = useState('');
  const [binLocation, setBinLocation] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // 获取库存数据
  const fetchInventoryData = async () => {
    try {
      setLoading(true);
      const response = await axios.get(`${API_BASE_URL}/api/inventory`);
      setInventoryItems(response.data);
    } catch (error) {
      console.error('获取库存数据失败:', error);
      message.error('获取库存数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchInventoryData();
  }, []);

  const columns: ColumnsType<InventoryItem> = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      render: (_, __, index) => (currentPage - 1) * pageSize + index + 1,
    },
    {
      title: '物品编号',
      dataIndex: 'code',
      key: 'code',
      width: 100,
      render: (text) => (
        <span style={{ color: '#1890ff', cursor: 'pointer' }}>
          {text}
        </span>
      ),
    },
    {
      title: '物品名称',
      dataIndex: 'name',
      key: 'name',
      width: 120,
    },
    {
      title: '分类',
      dataIndex: 'cate',
      key: 'cate',
      width: 100,
    },
    {
      title: '预警数量',
      dataIndex: 'warning',
      key: 'warning',
      width: 100,
    },
    {
      title: '仓库',
      dataIndex: 'warehouse',
      key: 'warehouse',
      width: 80,
    },
    {
      title: '库区',
      dataIndex: 'reservoir',
      key: 'reservoir',
      width: 80,
      render: (text) => (
        <span style={{ color: '#1890ff', cursor: 'pointer' }}>
          {text}
        </span>
      ),
    },
    {
      title: '库位',
      dataIndex: 'location',
      key: 'location',
      width: 80,
      render: (text) => (
        <span style={{ color: '#1890ff', cursor: 'pointer' }}>
          {text}
        </span>
      ),
    },
    {
      title: '创建人',
      dataIndex: 'add',
      key: 'add',
      width: 100,
    },
    {
      title: '创建时间',
      dataIndex: 'addtime',
      key: 'addtime',
      width: 120,
    },
  ];

  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: InventoryItem[]) => {
      console.log('selectedRowKeys:', selectedRowKeys, 'selectedRows:', selectedRows);
    },
  };

  const handleSearch = () => {
    // 搜索逻辑
    console.log('搜索:', { customerName, itemName, binLocation });
  };

  const handleReset = () => {
    setCustomerName('');
    setItemName('');
    setBinLocation('');
  };

  // 过滤数据
  const filteredItems = inventoryItems.filter(item => {
    const matchesCustomer = !customerName || item.add.toLowerCase().includes(customerName.toLowerCase());
    const matchesItem = !itemName || item.name.toLowerCase().includes(itemName.toLowerCase());
    const matchesBin = !binLocation || item.location.includes(binLocation);
    return matchesCustomer && matchesItem && matchesBin;
  });

  // 分页数据
  const startIndex = (currentPage - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const paginatedItems = filteredItems.slice(startIndex, endIndex);

  return (
    <div style={{ padding: "20px", height: "calc(100vh - 64px)", overflow: "hidden" }}>
      {/* 搜索区域 */}
      <div
        style={{
          backgroundColor: "#fff",
          padding: "20px",
          marginBottom: "20px",
          borderRadius: "4px"
        }}
      >
        <Input
          placeholder="请输入客户名称"
          value={customerName}
          onChange={(e) => setCustomerName(e.target.value)}
          style={{ width: 200, marginRight: 16 }}
          suffix={<SearchOutlined />}
        />
        <Input
          placeholder="物品名称"
          value={itemName}
          onChange={(e) => setItemName(e.target.value)}
          style={{ width: 200, marginRight: "auto" }}
          suffix={<SearchOutlined />}
        />
        <Button
          type="primary"
          style={{ marginRight: 8 }}
          onClick={handleSearch}
        >
          搜索
        </Button>
        <Button onClick={handleReset}>重置</Button>
      </div>

      {/* 表格区域 */}
      <Table
        columns={columns}
        dataSource={paginatedItems}
        rowKey="id"
        rowSelection={rowSelection}
        bordered
        loading={loading}
        pagination={{
          current: currentPage,
          pageSize: pageSize,
          total: filteredItems.length,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) =>
            `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          onChange: (page, size) => {
            setCurrentPage(page);
            setPageSize(size || 10);
          },
          onShowSizeChange: (current, size) => {
            setCurrentPage(1);
            setPageSize(size);
          },
          pageSizeOptions: ['10', '20', '50', '100'],
          showLessItems: false,
          showPrevNextJumpers: true,
        }}
        scroll={{ x: 1000, y: "calc(100vh - 500px)" }}
      />
    </div>
  );
};

export default Query;
